<?php

namespace plugins\yongtai;

use tree\Tree;

class Utils
{
    static function OneDay($date_str, $toStr = false)
    {
        $int_date = strtotime(trim($date_str));
        $start_time = strtotime(date("Y-m-d", $int_date));
        $end_time = $start_time + 60 * 60 * 24;
        $between_datetime = [$start_time, $end_time];
        return $toStr ? implode(',', $between_datetime) : $between_datetime;
    }

    // $date_str => 2020-20-20
    static function BetweenDate($date_str, $date_type = 'OneDay')
    {
        //        $beginThismonth = mktime(0, 0, 0, date('m'), 1, date('Y'));
        //        $endThismonth = mktime(23, 59, 59, date('m'), date('t'), date('Y'));
        //        $m = date('Y - m - d', mktime(0, 0, 0, date('m') - 1, 1, date('Y')));
        //        $t = date('t', strtotime($t = date('t', strtotime($t = date('t', strtotime($m));
        //
        if (empty($date_str)) {
            return [0, time()];
        }
        $between_datetime = [];
        switch ($date_type) {
            case "OneDay":
                $int_date = strtotime(trim($date_str));
                $start_time = strtotime(date("Y-m-d", $int_date));
                $end_time = $start_time + 60 * 60 * 24;
                $between_datetime = [$start_time, $end_time];
                break;
            case "Range":
                $between_datetime = [];
                $arr_date = explode(' - ', $date_str);
                foreach ($arr_date as $date) {
                    $between_datetime[] = strtotime(trim($date));
                }
                break;
        }

        return $between_datetime;
    }

    static function ArrFormatThumb($arr, $post_fix_url = '', $key = "thumb", $source_key = '_thumb', $def_thumb_url = "", $debug = false)
    {
        $list = [];
        foreach ($arr as $item) {
            $_item = $item;
            if (isset($item[$key]) and $item[$key]) {
                if (substr($item[$key], 0, 7) == "http://" or substr($item[$key], 0, 8) == "https://" or substr($item[$key], 0, 3) == '://' or substr($item[$key], 0, 2) == '//') {
                    $_item[$key] = $item[$key] != "" ? $post_fix_url . $item[$key] : "";
                    $_item[$source_key] = $item[$key];
                } else {
                    $_item[$key] = $post_fix_url . $item[$key];
                    $_item[$source_key] = $item[$key];
                }
            } else {
                $_item[$key] = $def_thumb_url;
                $_item[$source_key] = "";
            }
            $list[] = $_item;
        }
        if ($debug) var_dump($list);
        return $list;
    }

    static function FormatThumb($data, $post_fix_url = '', $key = 'thumb', $source_key = '_thumb', $def_thumb_url = "", $debug = false)
    {
        $thumb = $data[$key];
        if (isset($data[$key]) and $data[$key]) {
            if (substr($thumb, 0, 7) == "http://" or substr($thumb, 0, 8) == "https://" or substr($thumb, 0, 3) == '://' or substr($thumb, 0, 2) == '//') {
                $data[$key] = $thumb;
                $data[$source_key] = $thumb;
            } else {
                $data[$key] = $post_fix_url . $thumb;
                $data[$source_key] = $thumb;
            }
        } else {
            $data[$key] = $def_thumb_url;
            $data[$source_key] = '';
        }
        if ($debug) var_dump($data);
        return $data;
    }

    /**
     * @name 围栏算法，判断一个坐标，是否在围栏里面.如：['113.664673,34.810146','113.681667,34.796896','113.69231,34.794711','113.702009,34.809159']
     * @param array $fences 围栏，是一组坐标数组 如：113.674458,34.804719
     * @param string $point 要判断的坐标
     * @return bool
     * @author macnie <mac@lenmy.com>
     */
    static function InWall($fences, $point)
    {
        $nvert = count($fences);
        $vertx = [];
        $verty = [];
        list($testy, $testx) = explode(',', $point);
        foreach ($fences as $r) {
            list($lng, $lat) = explode(',', $r);
            $vertx[] = $lat;
            $verty[] = $lng;
        }

        $c = 0;
        for ($i = 0, $j = $nvert - 1; $i < $nvert; $j = $i++) {
            if ((($verty[$i] > $testy) != ($verty[$j] > $testy)) && ($testx < ($vertx[$j] - $vertx[$i]) * ($testy - $verty[$i]) / ($verty[$j] - $verty[$i]) + $vertx[$i])) $c = !$c;
        }
        return $c;
    }

    static function GeneratorOrderSn($postfix = '')
    {
        $order_id_main = date('YmdHis') . rand(10000000, 99999999);
        $order_id_len = strlen($order_id_main);
        $order_id_sum = 0;
        for ($i = 0; $i < $order_id_len; $i++) {
            $order_id_sum += (int)(substr($order_id_main, $i, 1));
        }
        $sn = $order_id_main . str_pad((100 - $order_id_sum % 100) % 100, 2, '0', STR_PAD_LEFT);
        return $postfix . $sn;
    }

    static function Same($arr, $same_key, array $sum_key_arr)
    {
        $list = [];
        foreach ($arr as $item) {
            if (isset($new[$item[$same_key]])) {
                foreach ($sum_key_arr as $sum_kay) $list[$item[$same_key]][$sum_kay] += $item[$sum_kay];
            } else {
                foreach ($sum_key_arr as $sum_kay) $list[$item[$same_key]] = $item[$sum_kay];
            }
        }
        return $list;
    }

    public static function CURL($url, $post = '', $cookie = '', $returnCookie = 0)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.1; Trident/6.0)');
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        curl_setopt($curl, CURLOPT_REFERER, "http://XXX");
        if ($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, http_build_query($post));
        }
        if ($cookie) {
            curl_setopt($curl, CURLOPT_COOKIE, $cookie);
        }
        curl_setopt($curl, CURLOPT_HEADER, $returnCookie);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)) {
            return curl_error($curl);
        }
        curl_close($curl);
        if ($returnCookie) {
            list($header, $body) = explode("\r\n\r\n", $data, 2);
            preg_match_all("/Set\-Cookie:([^;]*);/", $header, $matches);
            $info['cookie'] = substr($matches[1][0], 1);
            $info['content'] = $body;
            return $info;
        } else {
            return $data;
        }
    }

    static function RandStr($length)
    {
        $str = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
        $len = strlen($str) - 1;
        $randstr = '';
        for ($i = 0; $i < $length; $i++) {
            $num = mt_rand(0, $len);
            $randstr .= $str[$num];
        }
        return $randstr;
    }

    static function Week($start_week, $week_name = ['星期一', '星期二', '星期三', '星期四', '星期五', '星期六', '星期日'])
    {
        $list = [];
        for ($i = 0; $i < 7; $i++) {
            $start_week -= 1;
            $_item = [];
            $_item['key'] = $i;
            $_item['name'] = $week_name[$start_week];
            $list[] = $_item;
            if ($start_week <= 0) $start_week = 7;
        }
        return $list;
    }

    static function ArrSort($arr, $key = 'key')
    {
        $keys = array_column($arr, $key);
        array_multisort($keys, SORT_DESC, $arr);
        return $arr;
    }

    static function VerifyIdCard($id_code)
    {
        $id = strtoupper($id_code);
        $regx = "/(^\d{15}$)|(^\d{17}([0-9]|X)$)/";

        $arr_split = [];
        if (!preg_match($regx, $id)) {
            return false;
        }

        if (15 == strlen($id)) {
            // 检查15位
            $regx = "/^(\d{6})+(\d{2})+(\d{2})+(\d{2})+(\d{3})$/";

            @preg_match($regx, $id, $arr_split);
            // 检查生日日期是否正确
            $dtm_birth = "19" . $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];

            if (!strtotime($dtm_birth)) {

                return false;
            } else {
                return true;
            }
        } else {
            // 检查18位
            $regx = "/^(\d{6})+(\d{4})+(\d{2})+(\d{2})+(\d{3})([0-9]|X)$/";
            @preg_match($regx, $id, $arr_split);

            $dtm_birth = $arr_split[2] . '/' . $arr_split[3] . '/' . $arr_split[4];

            //检查生日日期是否正确
            if (!strtotime($dtm_birth)) {
                return false;
            } else {

                //检验18位身份证的校验码是否正确。
                //校验位按照ISO 7064:1983.MOD 11-2的规定生成，X可以认为是数字10。
                $arr_int = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                $arr_ch = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
                $sign = 0;

                for ($i = 0; $i < 17; $i++) {
                    $b = (int)$id[$i];
                    $w = $arr_int[$i];
                    $sign += $b * $w;
                }
                $n = $sign % 11;
                $val_num = $arr_ch[$n];

                if ($val_num != substr($id, 17, 1)) {
                    return false;
                } else {
                    return true;
                }
            }
        }
    }

    static function IsMobilePhone($mobile_phone)
    {
        $chars = "/^13[0-9]{1}[0-9]{8}$|15[0-9]{1}[0-9]{8}$|18[0-9]{1}[0-9]{8}$|17[0-9]{1}[0-9]{8}$/";
        if (preg_match($chars, $mobile_phone)) {
            return true;
        }
        return false;
    }

    static function SendEmail($to, $title, $message)
    {
        $headers = "From: 官方网站";
        return mail($to, $title, $message, $headers);
    }

    // 递归重组
    static function Recursion($data, $pid = 0, $level = 0, $p_key = 'article_category_id', $c_key = "children", $i_key = "id", $callable = null)
    {
        $list = [];
        foreach ($data as $v) {
            if ($v[$p_key] == $pid) {
                $v['level'] = $level;
                $v[$c_key] = self::Recursion($data, $v[$i_key], $level + 1);
                if ($callable)
                    $v['callable'] = $callable($data, $v[$i_key], $level + 1);
                $list[] = $v;
            }
        }
        return $list;
    }


    // 顺序树状结构
    static public $treeList = array();

    static public function Tree($data, $pid = 0, $level = 1, $p_key = "pid", $i_key = 'id', $callable = null)
    {
        foreach ($data as $v) {
            if ($v[$p_key] == $pid) {
                $v['level'] = $level;
                if ($callable)
                    $v['callable'] = $callable($data, $v[$i_key], $level + 1);
                self::$treeList[] = $v;
                self::Tree($data, $v[$i_key], $level + 1);
            }
        }
        return self::$treeList;
    }

    //驼峰命名转下划线命名
    static function ToUnderScore($str)
    {
        $dstr = preg_replace_callback('/([A-Z]+)/', function ($matchs) {
            return '_' . strtolower($matchs[0]);
        }, $str);
        return trim(preg_replace('/_{2,}/', '_', $dstr), '_');
    }

    //下划线命名到驼峰命名
    static function ToCamelCase($str)
    {
        $array = explode('_', $str);
        $result = $array[0];
        $len = count($array);
        if ($len > 1) {
            for ($i = 1; $i < $len; $i++) {
                $result .= ucfirst($array[$i]);
            }
        }
        return $result;
    }

    static function Map($arr, $callable, $then = null)
    {
        $_res = [];
        foreach ($arr as $item) $_res[] = $callable($item);
        if ($then) $_res = $then($_res);
        return $_res;
    }

    static public function TreeArray($objResult, $id = 0, $postfix_image_url = "")
    {
        $arrResult = Utils::ArrFormatThumb($objResult, $postfix_image_url);

        $tree = new Tree();
        $tree->init($arrResult);
        $categories = $tree->getTreeArray($id);
        return $categories;
    }

    static $arr_crumb = [];

    static function Crumb($id, $model, $key = "pid", $is_recursion = false): array
    {
        if (!$is_recursion) self::$arr_crumb = [];
        $now = $model->where(['id' => $id])->find()->toArray();
        if ($now and $now['pid'] != 0) {
            self::Crumb($now['pid'], $model, $key, true);
            if (!$is_recursion) self::$arr_crumb[] = $now;
        } else {
            self::$arr_crumb[] = $now;
        }
        return Utils::Map(
            self::$arr_crumb,
            function ($item) use ($id) {
                if ($item['pid'] == 0 or $id == $item['id']) {
                    $pid = $item['id'];
                } else {
                    $pid = $item['pid'];
                }
                $item['url'] = cmf_plugin_url("yongtai://Home/News", ['pid' => $pid]);
                return $item;
            },
            function ($data) {
                array_unshift($data, ['title' => "首页", 'url' => "/"]);
                return $data;
            }
        );
    }
}
